package android.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import winkyle.woodenfish.android.service.MessageInfoService;
import winkyle.woodenfish.constant.CookieConstant;
import winkyle.woodenfish.model.dto.MessageDto;
import winkyle.woodenfish.model.vo.MessageVo;
import winkyle.woodenfish.util.CookieUtil;
import winkyle.woodenfish.util.PathUtil;
import winkyle.woodenfish.util.ResultUtil;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/message")
public class MessageInfoApi {
	private final Logger logger= LoggerFactory.getLogger(MessageInfoApi.class);
	@Autowired
	private MessageInfoService messageInfoService;
	
	@GetMapping(value = "/messageInfoByUserId")
    public Object getMessageInfoByUserId(int page,HttpServletRequest httpServletRequest) {	
		logger.info("获取第{}页的消息列表",page);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		List<MessageDto> messageDtos = messageInfoService.findMessageInfoByUserId(CookieUtil.get(httpServletRequest, CookieConstant.LONGIN_KEY).getValue(), page);
		List<MessageVo> messageVos = new ArrayList<MessageVo>();
		for (MessageDto messageDto : messageDtos) {
			MessageVo messageVo = new MessageVo();
			messageVo.setTitle(messageDto.getTitle());
			messageVo.setContent(messageDto.getContent());
			if (messageDto.getImageUrl()!=null) {
				messageVo.setImageUrl(PathUtil.getAccessPath(httpServletRequest)+messageDto.getImageUrl());
			}else {
				messageVo.setImageUrl(null);
			}
			messageVo.setDescription(messageDto.getDescription());
			messageVo.setLinkAddress(messageDto.getLinkAddress());
			messageVo.setDate(simpleDateFormat.format(messageDto.getUpdateTime()));
			messageVos.add(messageVo);
		}
		return ResultUtil.success(messageVos);
    }
}
